package com.atguigu.gmall.util;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Set;

/**
 * @author : ranzlupup
 * @since : 2023/6/2 09:07
 */
public class PhoenixUtils {

    /**
     * 写出数据到Phoenix
     *
     * @param connection Phoenix连接
     * @param sinkTable  表名   tn
     * @param data       数据   {"id":"1001","name":"zhangsan","sex":"male"}
     */
    public static void upsertValues(DruidPooledConnection connection, String sinkTable, JSONObject data) throws SQLException {
        // 1.拼接SQL语句: upsert into db.tn(id,name,sex) values('1001','zhangsan','male')
        Set<String> columns = data.keySet();
        Collection<Object> values = data.values();
        StringBuilder sql = new StringBuilder("upsert into ")
                .append(MyConfig.HBASE_SCHEMA)
                .append(".")
                .append(sinkTable)
                .append("(")
                .append(StringUtils.join(columns, ","))
                .append(") values ('")
                .append(StringUtils.join(values, "','"))
                .append("')");

        // 2.预编译SQL
        PreparedStatement preparedStatement = connection.prepareStatement(sql.toString());

        // 3.执行SQL
        preparedStatement.execute();
        connection.commit();

        // 4.释放资源
        preparedStatement.close();
    }


}
